package com.example.springboot.service;

import com.example.springboot.entity.MerchantOrder;
import com.example.springboot.entity.Merchant;
import com.example.springboot.mapper.MerchantMapper;
import com.example.springboot.mapper.MerchantOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class MerchantOrderService {

    private static final Logger logger = LoggerFactory.getLogger(MerchantOrderService.class);

    @Autowired
    private MerchantOrderMapper merchantOrderMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    public List<MerchantOrder> findAll(int page, int size, String role, String username, String orderId, String status, String serviceType) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        int offset = (page - 1) * size;
        if (offset < 0) {
            logger.warn("Invalid page number: {}, setting offset to 0", page);
            offset = 0;
        }
        if (size <= 0) {
            logger.warn("Invalid size: {}, defaulting to 10", size);
            size = 10;
        }

        logger.info("Fetching orders for role: {}, username: {}, page: {}, size: {}, orderId: {}, status: {}, serviceType: {}",
                role, decodedUsername, page, size, orderId, status, serviceType);
        try {
            if ("ADMIN".equals(role)) {
                String adminRole = merchantOrderMapper.findAdminRoleByUsername(decodedUsername);
                if (adminRole == null) {
                    logger.error("No role found for username: {}", decodedUsername);
                    throw new IllegalArgumentException("管理员用户不存在或角色未定义");
                }
                if ("super".equals(adminRole)) {
                    logger.info("Super admin access: retrieving all orders");
                    return merchantOrderMapper.findAll(offset, size, orderId, status, serviceType);
                } else {
                    Integer adminId = getAdminId(decodedUsername);
                    return merchantOrderMapper.findByAdminId(offset, size, adminId, orderId, status, serviceType);
                }
            } else {
                Integer adminId = getAdminId(decodedUsername);
                return merchantOrderMapper.findByAdminId(offset, size, adminId, orderId, status, serviceType);
            }
        } catch (Exception e) {
            logger.error("Failed to fetch orders for page: {}, size: {}, role: {}, username: {}", page, size, role, decodedUsername, e);
            throw new RuntimeException("获取订单列表失败: " + e.getMessage(), e);
        }
    }

    public int getTotalOrders(String role, String username, String orderId, String status, String serviceType) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        try {
            if ("ADMIN".equals(role)) {
                String adminRole = merchantOrderMapper.findAdminRoleByUsername(decodedUsername);
                if (adminRole == null) {
                    logger.error("No role found for username: {}", decodedUsername);
                    throw new IllegalArgumentException("管理员用户不存在或角色未定义");
                }
                if ("super".equals(adminRole)) {
                    logger.info("Super admin access: retrieving total count of all orders");
                    return merchantOrderMapper.getTotalOrders(orderId, status, serviceType);
                } else {
                    Integer adminId = getAdminId(decodedUsername);
                    return merchantOrderMapper.getTotalOrdersByAdminId(adminId, orderId, status, serviceType);
                }
            } else {
                Integer adminId = getAdminId(decodedUsername);
                return merchantOrderMapper.getTotalOrdersByAdminId(adminId, orderId, status, serviceType);
            }
        } catch (Exception e) {
            logger.error("Failed to get total orders for role: {}, username: {}", role, decodedUsername, e);
            throw new RuntimeException("获取订单总数失败: " + e.getMessage(), e);
        }
    }

    public MerchantOrder findById(Integer orderId, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        MerchantOrder order = merchantOrderMapper.findById(orderId);
        if (order == null) {
            logger.warn("Order not found for orderId: {}", orderId);
            throw new IllegalArgumentException("订单不存在");
        }

        if ("ADMIN".equals(role)) {
            String adminRole = merchantOrderMapper.findAdminRoleByUsername(decodedUsername);
            if ("common".equals(adminRole)) {
                Integer adminId = getAdminId(decodedUsername);
                Merchant merchant = merchantMapper.findByIds(order.getMerchantId());
                if (merchant == null || !merchant.getAdminId().equals(adminId)) {
                    logger.warn("Permission denied for username: {} to view orderId: {}", decodedUsername, orderId);
                    throw new IllegalArgumentException("无权限查看该订单");
                }
            }
        }
        return order;
    }

    public MerchantOrder insert(MerchantOrder merchantOrder, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        Merchant merchant = merchantMapper.findByIds(merchantOrder.getMerchantId());
        if (merchant == null) {
            logger.error("Merchant not found for merchantId: {}", merchantOrder.getMerchantId());
            throw new IllegalArgumentException("指定的商家不存在");
        }

        if ("ADMIN".equals(role)) {
            String adminRole = merchantOrderMapper.findAdminRoleByUsername(decodedUsername);
            if ("common".equals(adminRole)) {
                Integer adminId = getAdminId(decodedUsername);
                if (!merchant.getAdminId().equals(adminId)) {
                    logger.warn("Permission denied for username: {} to create order for merchantId: {}", decodedUsername, merchant.getMerchantId());
                    throw new IllegalArgumentException("无权限为该商家创建订单");
                }
            }
        }

        merchantOrder.setCreatedAt(Timestamp.valueOf(LocalDateTime.now()));
        merchantOrder.setUpdatedAt(Timestamp.valueOf(LocalDateTime.now()));
        merchantOrderMapper.insert(merchantOrder);
        return merchantOrder;
    }

    public MerchantOrder update(MerchantOrder merchantOrder, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        MerchantOrder existingOrder = merchantOrderMapper.findById(merchantOrder.getOrderId());
        if (existingOrder == null) {
            logger.warn("Order not found for orderId: {}", merchantOrder.getOrderId());
            throw new IllegalArgumentException("订单不存在");
        }

        Merchant merchant = merchantMapper.findByIds(merchantOrder.getMerchantId());
        if (merchant == null) {
            logger.error("Merchant not found for merchantId: {}", merchantOrder.getMerchantId());
            throw new IllegalArgumentException("指定的商家不存在");
        }

        if ("ADMIN".equals(role)) {
            String adminRole = merchantOrderMapper.findAdminRoleByUsername(decodedUsername);
            if ("common".equals(adminRole)) {
                Integer adminId = getAdminId(decodedUsername);
                if (!merchant.getAdminId().equals(adminId)) {
                    logger.warn("Permission denied for username: {} to update orderId: {}", decodedUsername, merchantOrder.getOrderId());
                    throw new IllegalArgumentException("无权限操作该订单");
                }
            }
        }

        merchantOrder.setUpdatedAt(Timestamp.valueOf(LocalDateTime.now()));
        merchantOrderMapper.update(merchantOrder);
        return merchantOrder;
    }

    public void deleteById(Integer orderId, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        MerchantOrder order = merchantOrderMapper.findById(orderId);
        if (order == null) {
            logger.warn("Order not found for orderId: {}", orderId);
            throw new IllegalArgumentException("订单不存在");
        }

        if ("ADMIN".equals(role)) {
            String adminRole = merchantOrderMapper.findAdminRoleByUsername(decodedUsername);
            if ("common".equals(adminRole)) {
                Integer adminId = getAdminId(decodedUsername);
                Merchant merchant = merchantMapper.findByIds(order.getMerchantId());
                if (merchant == null || !merchant.getAdminId().equals(adminId)) {
                    logger.warn("Permission denied for username: {} to delete orderId: {}", decodedUsername, orderId);
                    throw new IllegalArgumentException("无权限删除该订单");
                }
            }
        }

        try {
            merchantOrderMapper.deleteById(orderId);
        } catch (Exception e) {
            logger.error("Failed to delete orderId: {} for role: {}, username: {}", orderId, role, decodedUsername, e);
            throw new RuntimeException("无法删除订单，可能由于数据库约束或数据不一致", e);
        }
    }

    private void validateInput(String role, String username) {
        if (username == null || username.trim().isEmpty()) {
            logger.error("Username is null or empty");
            throw new IllegalArgumentException("Username header is required");
        }
        if (role == null || role.trim().isEmpty()) {
            logger.error("Role is null or empty");
            throw new IllegalArgumentException("Role header is required");
        }
    }

    private Integer getAdminId(String username) {
        Integer adminId = merchantOrderMapper.findAdminIdByUsername(username);
        if (adminId == null) {
            logger.error("No admin ID found for username: {}", username);
            throw new IllegalArgumentException("无法获取管理员 ID，用户名可能不存在");
        }
        return adminId;
    }

    private String decodeUsername(String username) {
        if (username == null) {
            return null;
        }
        try {
            return URLDecoder.decode(username, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            logger.warn("Failed to decode username: {}, using original value", username, e);
            return username;
        }
    }
}